#include "QLight.h"



QLight::QLight(QWidget *parent) : QWidget(parent)
{
    initUI();
    // connect(timer,SIGNAL(timeout),this,SLOT(switchLedIndicator));
    connect(timer, &QTimer::timeout, this, QOverload<>::of(&QLight::switchLedIndicator));
}

void QLight::Open()
{
    r_init = false;
    lit = true;
    timer->stop();
    repaint();
}

void QLight::Close()
{
    r_init = false;
    r_init = true;
    timer->stop();
    repaint();
}

void QLight::Default()
{
    r_init = true;
    timer->stop();
    repaint();
}

void QLight::Error()
{
    r_init = false;
    timer->start(500);
    setOnColor(Qt::red);
    repaint();
}

void QLight::Blink(bool st)
{
    timer->start(500);
    if(st){
        setOnColor(Qt::green);
        Open();
    }
    repaint();
}

void QLight::StopBlink()
{
     timer->stop();
}

void QLight::initUI()
{
    setFixedSize(28, 28);
    lit = false;
    r_init = true;
    ledDefault=Qt::yellow;
    ledOnColor=Qt::green;
    ledOffColor=Qt::gray;
    ledOnPattern = Qt::SolidPattern;
    ledOffPattern = Qt::SolidPattern;
    ledSize=20;
    timer = new QTimer();
    repaint();
}

void QLight::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    // 绘制准备工作 启用反锯齿
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    QPainter p(this);
    if(r_init){
        p.setBrush(QBrush(ledDefault, ledOnPattern));
    }else {
        lit ?  p.setBrush(QBrush(ledOnColor, ledOnPattern)) : p.setBrush(QBrush(ledOffColor, ledOffPattern));
    }
    p.drawEllipse(0,0,ledSize,ledSize);
}

// 取反灯
void QLight::switchLedIndicator() {
  lit = ! lit;
  repaint();
}

// 设置状态
void QLight::setState(bool state)
{
    lit = state;
    repaint();
}

void QLight::toggle()
{
    lit = ! lit;
    repaint();
}

void QLight::setOnColor(QColor onColor)
{
    ledOnColor=onColor;
    repaint();
}
void QLight::setOffColor(QColor offColor)
{
    ledOffColor=offColor;
    repaint();
}
void QLight::setOnPattern(Qt::BrushStyle onPattern)
{
    ledOnPattern=onPattern;
    repaint();
}
void QLight::setOffPattern(Qt::BrushStyle offPattern)
{
    ledOffPattern=offPattern;
    repaint();
}
void QLight::setLedSize(int size)
{
    ledSize=size;
    setFixedSize(size+10, size+10);
    repaint();
}

